﻿using Corina.Datamodel.Entities;
using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Linq;
using Corina.Commands;
using Corina.Enumerations;
using System.Text.RegularExpressions;

namespace Corina.Cydee.Apphub.Viewmodels
{
    public class AutoResolveConfigViewmodel : ViewmodelBase
    {
        public AutoResolveConfigViewmodel()
        {
            DeviceClient.GetAutoResolveItemsCompleted += GetAutoResolveItemsCompleted;
            DeviceClient.InsertAutoResolveCompleted += InsertAutoResolveCompleted;
            DeviceClient.UpdateAutoResolveCompleted += UpdateAutoResolveCompleted;
            DeviceClient.RemoveAutoResolveCompleted += RemoveAutoResolveCompleted;
            DeviceClient.GetDeviceKindItemsCompleted += GetDeviceKindItemsCompleted;
            if (DataContext.IsValid)
            {
                DeviceClient.GetDeviceKindItemsAsync();
                LoadData();
            }
        }

        private void GetDeviceKindItemsCompleted(object sender, DataService.GetDeviceKindItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                DeviceKindCollection = new ObservableCollection<DeviceKindInfo>(e.Result.Entities.OfType<DeviceKindInfo>());
            }
        }

        private void RemoveAutoResolveCompleted(object sender, DataService.RemoveAutoResolveCompletedEventArgs e)
        {
            LoadData();
        }

        private void UpdateAutoResolveCompleted(object sender, DataService.UpdateAutoResolveCompletedEventArgs e)
        {
            LoadData();
        }

        private void InsertAutoResolveCompleted(object sender, DataService.InsertAutoResolveCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == ResultValue.Succeed)
                {

                    Operation = EntityOperation.None;
                    DeviceSn = string.Empty;

                    Index = 1;
                    LoadData();
                }
                else
                {
                    MessageBox.Show(e.Result.Result.ToString());
                }
            }
        }

        private void GetAutoResolveItemsCompleted(object sender, DataService.GetAutoResolveItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                var items = (from t in e.Result.DataObjects
                             select new
                             {
                                 ItemIndex = t["ROW_NUMBER"],
                                 Id = t["Id"],
                                 DeviceSn = (string)t["DeviceSn"],
                                 Kind = (string)t["Kind"],
                                 AutoResolve = Convert.ToBoolean(t["AutoResolve"])
                             });
                ItemsCollection = new ObservableCollection<object>(items);
                ItemsCount = e.Result.TotalCount;
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
            IsBusy = false;
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            DeviceClient.GetAutoResolveItemsAsync(Account, Password, DeviceKindId, SearchDeviceSn, Index, 20);
        }

        #region Collection
        private ObservableCollection<object> _itemsCollection;
        public ObservableCollection<object> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
            }
        }

        private ObservableCollection<DeviceKindInfo> _deviceKindCollection;
        public ObservableCollection<DeviceKindInfo> DeviceKindCollection
        {
            get { return _deviceKindCollection; }
            set
            {
                _deviceKindCollection = value;
                RaisePropertyChanged(() => DeviceKindCollection);
            }
        }
        #endregion

        #region Search
        
        public int DeviceKindId
        {
            get { return SelectedDeviceKind == null ? 0 : SelectedDeviceKind.Id; }
        }

        private DeviceKindInfo _selectedDeviceKind;
        public DeviceKindInfo SelectedDeviceKind
        {
            get { return _selectedDeviceKind; }
            set {
                _selectedDeviceKind = value;
                RaisePropertyChanged(() => SelectedDeviceKind);
                RaisePropertyChanged(() => DeviceKindId);
            }
        }

        private string _searchDeviceSn = string.Empty;
        public string SearchDeviceSn
        {
            get { return _searchDeviceSn; }
            set
            {
                _searchDeviceSn = value;
                RaisePropertyChanged(() => SearchDeviceSn);
            }
        }
        #endregion

        #region Update
        private string _deviceSn = string.Empty;
        public string DeviceSn
        {
            get { return _deviceSn; }
            set
            {
                _deviceSn = value;
                RaisePropertyChanged(() => DeviceSn);
                RaisePropertyChanged(() => SubmitCommand);
            }
        }
        #endregion

        #region Command
        public ICommand LoadCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Index = 1;
                        LoadData();
                    }
                };
            }
        }

        public ICommand ChangeCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(GetObjectPropertyValue(t, "Id"));
                    bool flag = Convert.ToBoolean(GetObjectPropertyValue(t, "AutoResolve"));

                    DeviceClient.UpdateAutoResolveAsync(Account, Password, id, !flag);
                });
            }
        }

        public ICommand InsertCommand
        {
            get {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        Operation = EntityOperation.Insert;
                    }
                };
            }
        }

        public ICommand SubmitCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return Regex.IsMatch(DeviceSn, "[0-9]{9}") && DeviceSn.Length == 9; },
                    ExecuteCallback = delegate
                    {
                        DeviceClient.InsertAutoResolveAsync(Account, Password, DeviceSn);
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        DeviceSn = string.Empty;
                        Operation = EntityOperation.None;
                    }
                };
            }
        }

        public ICommand RemoveCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    if (ShowConfirm(Language.LanguageKeys.IDS_DELETE_CONFIRM) == MessageBoxResult.OK)
                    {
                        int id = (int)t;

                        DeviceClient.RemoveAutoResolveAsync(Account, Password, id);
                    }
                });
            }
        }
        #endregion
    }
}
